<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 
 **/
class Model extends CI_Model{

    function __construct(){
        parent::__construct();
    }

    public function getWebHtmlDoc($url){
        require_once APPPATH.'libraries/simple_html_dom.php';
        //$url = str_replace('//', '/', $url);

        $html = file_get_html($url);

        while (empty($html)) {
            if(!isset($i)) $i = 1;

            sleep(2);
            $html = file_get_html($url);
            if(!empty($html) || $i > 5) break;
            $i++;
        }
        if(empty($html)){
            $sql = "insert dragon_error_log(log_cnt,log_type,create_time) values('".$this->db->escape_str('loaded html content failed.'.$url)."','fetch_web_error',".time().")";
            $this->db->simple_query($sql);
        }
        return $html;
    }

    /**
     * 下载图片
     * @param $imgUrl 图片网址
     * @params $destPath 图片保存地址
     **/
    public function downImg($imgUrl, $destPath){
        //$url = str_replace('//', '/', $imgUrl); 
        $url = $imgUrl;

        ob_start();
        readfile($url);
        $img = ob_get_contents();
        ob_end_clean();

        $index = strrpos('/', $url);
        $imgName = substr($url, $index);

        $this->create_dirs_if_not_exist($destPath);
        $imgPath = $destPath.'/'.$imgName;
        $imgPath = str_replace('//', '/', $imgPath);

        $fileHandle = fopen($imgPath, 'w');
        fwrite($fileHandle, $img);
        fclose($fileHandle);

        return $imgPath;
    }

    public function  create_dirs_if_not_exist($path, $prefixPath = ''){
        if(!isset($path) || strlen(trim($path)) <= 0){
            return false;
        }
        $tmpPath = '';
        $p = explode('/', $path);
        $tmpPath = "$p[0]";//"$p[0]/$p[1]";
        for($i = 1; $i < count($p); $i++){
            $tmpPath = "$tmpPath/$p[$i]";

            if(!is_dir("$prefixPath$tmpPath") ){
                mkdir("$prefixPath$tmpPath", 0777);
            }

        }

    }
}

?>
